package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import com.gulimall.common.constant.AuthServerConstant;
import com.gulimall.common.exception.BizCodeEnum;
import com.gulimall.common.utils.R;
import com.gulimall.common.vo.MemberEntityVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
   @GetMapping("/sms/snedcode")
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 1，接口防刷

        //2 验证码再次校验 redis
        String string = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(string)){
            String s = string.split("_")[1];
            long pastTime = Long.parseLong(s);
            if(System.currentTimeMillis()-pastTime<60000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        String code1=code.substring(0,5);
       //TODO 开发环境中直接把验证码打印到控制台
       /*thirdPartFeignService.sendCode(phone,code1);*/
        System.out.println("验证码是"+code1);
        //redis缓存验证码，防止同一个phone在60秒内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
       return R.ok();
   }

    /**
     * TODO 重定向携带数据利用了session的原理，但是分布式下session有问题
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
   @PostMapping("/register")
    public String regist(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
       Map<String,String> errors=new HashMap<>();
        if(result.hasErrors()){
             errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

       //1, 校验验证码
       String code = vo.getCode();
       String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
       if(!StringUtils.isEmpty(s)){
           if(s.split("_")[0].equals(code)){
               //删除验证码
               redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
               //调用远程服务进行注册
               R register = memberFeignService.register(vo);
               if(register.getCode()==0){
                   //调用成功，返回登录页
                   return "redirect:http://auth.gulimall.com/login.html";
               }
               else {
                   //调用失败，返回注册页并显示错误信息
                   String msg = (String) register.get("msg");
                   errors.put("msg", msg);
                   redirectAttributes.addFlashAttribute("errors", errors);
                   return "redirect:http://auth.gulimall.com/reg.html";
               }
           }
           else {
               errors=new HashMap<>();
               errors.put("code","验证码错误");
               redirectAttributes.addFlashAttribute("errors",errors);
               return "redirect:http://auth.gulimall.com/reg.html";
           }
       }else {
           errors=new HashMap<>();
           errors.put("code","验证码错误");
           redirectAttributes.addFlashAttribute("errors",errors);
           return "redirect:http://auth.gulimall.com/reg.html";
       }

   }

   @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
       //远程登录
       R login = memberFeignService.login(vo);
       if(login.getCode()==0){
           MemberEntityVo data = login.getData(new TypeReference<MemberEntityVo>(){
           });
           session.setAttribute(AuthServerConstant.LOGIN_USER,data);
           return "redirect:http://gulimall.com";
       }
       else{
           String msg = (String) login.get("msg");
           Map<String, String> errors = new HashMap<>();
           errors.put("msg", msg);
           redirectAttributes.addFlashAttribute("errors", errors);
           return "redirect:http://auth.gulimall.com/login.html";
       }

   }
}
